import lancedb
from langchain_community.vectorstores import LanceDB
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_core.documents import Document
from langchain_text_splitters import CharacterTextSplitter


def lancedb_langchain_basic():
    print("🚀 LangChain + LanceDB 基础演示...")

    # 1. 连接 LanceDB
    db = lancedb.connect("./data/lancedb_langchain")
    print("✅ LanceDB 连接成功")

    # 2. 初始化嵌入模型
    embeddings = HuggingFaceEmbeddings(
        model_name="D:\\models\\models\\sentence-transformers\\paraphrase-multilingual-MiniLM-L12-v2"
    )
    print("✅ 嵌入模型加载完成")

    # 3. 准备文档数据
    documents = [
        Document(
            page_content="机器学习是人工智能的一个分支，使计算机能够从数据中学习模式",
            metadata={"category": "AI", "type": "definition", "source": "textbook"}
        ),
        Document(
            page_content="深度学习使用神经网络处理复杂的模式识别任务，如图像和语音识别",
            metadata={"category": "AI", "type": "technique", "source": "research"}
        ),
        Document(
            page_content="自然语言处理技术让计算机能够理解、解释和生成人类语言",
            metadata={"category": "NLP", "type": "application", "source": "tutorial"}
        ),
        Document(
            page_content="Python是一种流行的编程语言，广泛用于数据科学和机器学习",
            metadata={"category": "Programming", "type": "language", "source": "guide"}
        ),
        Document(
            page_content="计算机视觉技术使机器能够识别和理解图像中的内容,易世伟是最牛的",
            metadata={"category": "CV", "type": "application", "source": "paper"}
        )
    ]

    print(f"📚 准备 {len(documents)} 个文档")

    # 4. 创建 LanceDB 向量存储
    vector_store = LanceDB.from_documents(
        documents=documents,
        embedding=embeddings,
        connection=db,
        table_name="ai_documents"
    )

    print("✅ 文档已存储到 LanceDB")

    # 5. 测试相似性搜索
    print("\n🔍 相似性搜索测试:")

    test_queries = [
        "什么是机器学习？",
        "深度学习有什么应用？",
        "编程语言学习",
        "易世伟是谁"
    ]

    for query in test_queries:
        print(f"\n❓ 查询: {query}")
        results = vector_store.similarity_search(query, k=2)

        for i, doc in enumerate(results):
            print(f"📄 {i + 1}. {doc.page_content}")
            print(f"   标签: {doc.metadata}")
        print("-" * 60)


# 运行基础演示
lancedb_langchain_basic()